﻿@model IEnumerable<A_Shop.Models.Producto>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutCliente.cshtml";

}
<form id="form_busqueda" data-bind="submit: buscar"> 
  <label> 
      <span>Buscar un producto: </span> 
      <input type="text" name="term" data-bind='value: term, valueUpdate: "afterkeydown"'/> 
  </label> 
</form>
<!-- ko if: term -->
<h2>Se ha buscado: <span data-bind="text: term"></span></h2>
<!-- /ko -->

<table style="background-color:rgba(255, 255, 255, 0.78)" class="table table-bordered">
    <tr class="success">
        <th>@Html.DisplayNameFor(model => model.Nombre)</th>
        <th>@Html.DisplayNameFor(model => model.Modelo)</th>
        <th>@Html.DisplayNameFor(model => model.Marca)</th>
        <th>@Html.DisplayNameFor(model => model.Precio)</th>
        <th>@Html.DisplayNameFor(model => model.Descripcion)</th>
        <th>@Html.DisplayNameFor(model => model.Foto)</th>
    </tr>

    <tbody data-bind="foreach: productos">
    <tr>
        <td><a href="~/Cliente/Detalle/id" target="_blank" data-bind="text: Nombre">TEMP</a></td>
        <td data-bind="text: Modelo"> XXX modelo</td>
        <td>
            <span data-bind="text: Marca.Nombre"></span>
            <img src="%3D" data-bind="attr:{src: Marca.Foto}"  height="200" width="200"></img>
        </td>
        <td data-bind="text: Precio"> PPPP </td>
        <td data-bind="text: Descripcion">descripcion</td>
        <td>
            <img src="%3D" width="200px" height="200px" data-bind="attr:{src: Foto}" />  
        </td>
    </tr>
    </tbody>
</table>

@section scripts {
    <script type="text/javascript">

    function ViewModel() {
        var self = this;
        self.productos = ko.observableArray();
        self.term = ko.observable("");

        self.productos.subscribe(function (newValue) {
            $.each(newValue, function (index, b) {
                b.Foto = ko.computed(function () {
                    return '@Url.Content("~/Content/productos/")' + b.id + '.jpg';
                });
            });
        });

        self.buscar = function () {
                $.ajax({
                    url: "@Url.Content("~/Api/ClienteApi/Buscar")",
                    data: { term: self.term() }, // no tengo información adicional que transmitir en el GET
                    success: function (data, textStatus, jqXHR) {
                    console.log("resultado", data);
                    self.productos(data);
                },
                dataType: "json"
            });

        }

        self.term.subscribe(function (newValue) { self.buscar(); });
    }

    $(document).ready(function () {
        vm.buscar();
    });

    var vm = new ViewModel();
    ko.applyBindings(vm);

    </script>
}

